package com.harboursoftware.xstorage.operations;

import java.io.InputStream;
import java.util.Map;

import org.apache.commons.io.input.CountingInputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ListMultimap;
import com.harboursoftware.xstorage.Constants;
import com.harboursoftware.xstorage.XStorageException;
import com.harboursoftware.xstorage.ac.AccessControlPolicy;
import com.harboursoftware.xstorage.ac.InvalidCannedAccessPolicyException;
import com.harboursoftware.xstorage.ac.Permission;
import com.harboursoftware.xstorage.fs.BucketNotExistException;
import com.harboursoftware.xstorage.fs.ObjectNotExistException;
import com.harboursoftware.xstorage.model.XBucket;
import com.harboursoftware.xstorage.model.XElement;
import com.harboursoftware.xstorage.model.XObject;
import com.harboursoftware.xstorage.model.XUser;
import com.harboursoftware.xstorage.results.EmptyContentResult;
import com.harboursoftware.xstorage.results.ErrorResult;
import com.harboursoftware.xstorage.results.Result;
import com.harboursoftware.xstorage.util.MultimapUtils;

public class PutObject extends Operation {
    private final static Logger log = LoggerFactory.getLogger(PutObject.class);
    private static XStorageException contentMD5DoesNotMatchException = new XStorageException();
    private static XStorageException contentLengthDoesNotMatchException = new XStorageException();

    @Override
    public Result execute(XUser requester, XElement element, ListMultimap<String, String> headers,
        Map<String, String> parameters) {
        // 测试s3 判断是否保存Content-Type,Cache-Control....
        // TODO : ETag 是MD5，是否可以使用FileSystem.getFileChecksum()来实现
        // TODO : 权限
        // TODO : 回滚的功能，当在fs中创建成功后，意外发送异常，必须回滚，把已经创建成功的bucket删除
        log.debug("excute");
        XObject object = (XObject) element;
        XBucket bucket = object.getBucket();

        try {
            fileSystem.loadBucketACP(bucket);

            AccessControlPolicy bucketAcp = bucket.getAcp();
            if (!bucketAcp.checkPermission(requester, getRequiredPermission())) {
                return ErrorResult.create(ErrorResult.Type.ACCESS_DENIED);
            }

            ListMultimap<String, String> headersNeededToSave = getHeadersNeededToSave(headers);
            object.setHeaders(headersNeededToSave);
            object.setOwner(requester);
            InputStream inputStream = object.getInputStream();
            CountingInputStream countingInputStream = null;
            if (headers.containsKey("Content-Length")) {
                countingInputStream = new CountingInputStream(inputStream);
                inputStream = countingInputStream;
            }
            object.setInputStream(inputStream);

            XUser bucketOwner = bucketAcp.getOwner();
            AccessControlPolicy objectAcp = getCannedAcpSpecifiedOnHeader(requester, bucketOwner, headers);
            object.setAcp(objectAcp);

            String actualMD5Digest = fileSystem.createObject(object);
            
            if (headers.containsKey("Content-MD5")) {
                // verify content md5
                String expectedMD5Digest = headers.get("Content-MD5").get(0);
                try {
                    // TODO:是否可以采购这里的代码，把try catch 改成直接由XStorageException 把 ErrorResult带到外层
                    verifyContentMD5(expectedMD5Digest, actualMD5Digest);
                } catch (XStorageException e) {
                    log.debug("Content-MD5 does not match,the digest expected is [{}], but actual is [{}]",
                        expectedMD5Digest, actualMD5Digest);
                    fileSystem.deleteObject(object);
                    return ErrorResult.create(ErrorResult.Type.INVALID_DIGEST);
                }
            }

            if (headers.containsKey("Content-Length")) {
                // verify content length
                int actualContentLength = countingInputStream.getCount();
                String expectedContentLength = headers.get("Content-Length").get(0);
                try {
                    verifyContentLength(expectedContentLength, actualContentLength);
                } catch (XStorageException e) {
                    // TODO:不能保证一定删除
                    log.debug("Content-Length does not match,the lenght expected is [{}], but actual is [{}]",
                        expectedContentLength, actualContentLength);
                    fileSystem.deleteObject(object);
                    return ErrorResult.create(ErrorResult.Type.INCOMPLETE_BODY);
                }
            }

        } catch (InvalidCannedAccessPolicyException e) {
            ErrorResult errorResult = ErrorResult.create(ErrorResult.Type.INVALID_ARGUMENT);
            errorResult.addOtherInfo("ArgumentName", Constants.REST_METADATA_ACL);
            errorResult.addOtherInfo("ArgumentValue", e.getInvaildCannedAccessPolicy());
            return errorResult;
        } catch (ObjectNotExistException e) {
            // ignore
        } catch (BucketNotExistException e) {
            return ErrorResult.create(ErrorResult.Type.NO_SUCH_BUCKET);
        } catch (XStorageException e) {
            log.error("error occured when put object", e);
            return ErrorResult.create(ErrorResult.Type.INTERNAL_ERROR);
        }
        return new EmptyContentResult();
    }

    @Override
    public Permission getRequiredPermission() {
        return Permission.WRITE;
    }

    /**
     * @param expected
     * @param actual
     * @throws XStorageException
     *             Content-MD5不匹配
     */
    private void verifyContentMD5(String expected, String actual) throws XStorageException {
        if (expected != null && !expected.equals(actual)) {
            throw contentMD5DoesNotMatchException;
        }
    }

    /**
     * 
     * @param expected
     * @param actual
     * @throws XStorageException
     *             Content-Length不匹配
     */
    private void verifyContentLength(String expected, int actual) throws XStorageException {
        if (expected != null && expected.equals(String.valueOf(actual))) {
            throw contentLengthDoesNotMatchException;
        }
    }

    private ListMultimap<String, String> getHeadersNeededToSave(ListMultimap<String, String> headers) {
        ListMultimap<String, String> headersNeededToSave = ArrayListMultimap.create();
        for (String key : headers.keySet()) {
            // TODO: post object 需要保持的头
            if (key.equals("Cache-Control") || key.equals("Content-Disposition") || key.equals("Content-Type")
                || key.equals("Expires") || key.startsWith("x-amz-meta-")) {
                headersNeededToSave.putAll(key, headers.get(key));
            }
        }
        return headersNeededToSave;
    }

    /**
     * @param headers
     * @return the AccessControlPolicy instance
     * @throws InvalidCannedAccessPolicyException
     *             when canned access policy specified on header is invaild
     */
    private AccessControlPolicy getCannedAcpSpecifiedOnHeader(XUser requester, XUser bucketOwner,
        ListMultimap<String, String> headers) throws InvalidCannedAccessPolicyException {
        String cannedAccessPolicyLabel = MultimapUtils.getFirstValue(headers, Constants.REST_METADATA_ACL);

        AccessControlPolicy cannedAccessPolicy =
            AccessControlPolicy.createCannedAccessPolicy(cannedAccessPolicyLabel, requester, bucketOwner);

        return cannedAccessPolicy;
    }
}
